<?php

/**
 *  @desc class Emo_Loader_Autoload
 *  auto load class when new Class in project
 * 
 */
require_once 'Emos/Loader/Interface.php';

class Emos_Loader_Autoloader implements Emos_Loader_Interface {
       
    protected $_class;
    /**
    * @desc __contruct
    * @param type $option 
    */
   
    public function __construct($option = array()) {
        
        if($option){
            $this->setOptions($option);
        }
    }

    public function autoload($class) {
        
            $classPath = $this->getClassPath($class);
            if (false !== $classPath && $this->checkFileExist($classPath)) {
                return include $classPath;
            }
        
        return false;
    }
    
    protected function checkFileExist($file){
        
        foreach(explode(';',ini_get('include_path')) as $k => $tryThis){
            
            //try each possible iteration of the file name and use the first one that comes up
            // name.class.php first
            $exists = file_exists($tryThis .DS. $file);
            if ($exists) return true;
            //ok that didn't work, try the other way around
            $exists = file_exists($tryThis . DS . 'class.' . $name . '.php');
            if ($exists) return true;
            //neither did that...let's try as an inc.php
            $exists = file_exists($tryThis . DS . $name . '.inc.php');
            if ($exists)return true;
        }
        return false;
    }
    
    protected function getClassPath($class){
        
        return strtr($class, '_\\', '//') . '.php';
    }
    
    protected function setOptions($options = array()){
        
        if($options){
            // Ensure library/ is on include_path
            set_include_path(implode(PATH_SEPARATOR, array(
                realpath(dirname($options['path'])),
                get_include_path(),
            )));
        }
    }
}